<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        * {
            padding: 0;
            margin: 0;
        }

        .shadow {
            width: 200px;
            height: 200px;
            background-color: rgba(0, 0, 0, 0.5);
            position: absolute;
            left: 100px;
            top: 100px;
        }
    </style>
</head>

<body>
    <div class="shadow"></div>
</body>
<script>
    // 元素拖拽   => 鼠标拖拽元素移动
    // 1. 先按下 => 选中该元素
    // 2. 再移动 => 元素跟随鼠标移动
    // 3. 再松开 => 元素不在跟随鼠标移动


    var shadow = document.getElementsByClassName("shadow")[0];
    var maxLeft = document.documentElement.clientWidth - shadow.clientWidth;
    var maxTop = document.documentElement.clientHeight - shadow.clientHeight;

    // 1. 先按下 => 选中该元素 => 记录按下的位置(鼠标相对于shadow的偏移)
    shadow.onmousedown = function (e) {
        var e = e || window.event;

        var posX = e.offsetX;
        var posY = e.offsetY;

        console.log(posX, posY);  //按下的位置


        // 2. 先按下再移动 => 元素跟随鼠标在文档中移动(相对于按下的位置移动)
        document.onmousemove = function (e) {
            var e = e || window.event;

            var x = e.pageX - posX;
            var y = e.pageY - posY;

            if (x < 0) x = 0;
            if (x > maxLeft) x = maxLeft;
            if (y < 0) y = 0;
            if (y > maxTop) y = maxTop;

            shadow.style.left = x + "px";
            shadow.style.top = y + "px";
        }

        document.onmouseup = function () {
            document.onmousemove = null;
        }

    }









</script>

</html>